package sevensoft.gz031.demos.web.interceptor;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import sevensoft.gz031.demos.web.response.R;
import sevensoft.gz031.demos.web.utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AdminInterceptor implements HandlerInterceptor {

    /**
     * 管理员权限拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if ("OPTIONS".equals(request.getMethod()))return true;
        response.setCharacterEncoding("utf-8");
        String token=request.getHeader("token");
        if (null==token){
            response.getWriter().write(JSON.toJSONString(R.accessNo("没有token")));
            return false;
        }else if (JwtUtil.checkSign(token)){
            return true;
        }else {
            response.getWriter().write(JSON.toJSONString(R.accessNo("您无权访问")));
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
